<template>
  <view class="main">
    <view class="address" @click="handleToAddress">
      <view class="address-content">
        <view class="address-null" v-if="!orderData.expressAddress">选择地址</view>
        <template v-else>
          <view class="iconfont icon-address"></view>
          <view class="address-info">
            <view class="address-text">{{ orderData.expressAddress }}</view>
            <view class="address-user">
              <text style="margin-right: 20rpx">{{ orderData.expressReceiverName }}</text>
              <text>{{ orderData.expressReceiverPhone }}</text>
            </view>
          </view>
        </template>
      </view>
      <view class="iconfont icon-more"></view>
    </view>
    <view class="products">

      <view class="cart-item" v-for="(item, index) in cartProductList" :key="index">
        <ProductOrder class="product-item" :product="item" >
        </ProductOrder>
      </view>
    </view>
    <view class="activity" >
      <template v-if="type === 1">
        <view class="activity-item">
          <view class="item-label"><text class="label-required">*</text>选择参与活动<text class="iconfont icon-info" @click="hintDialogShow = true"></text></view>
          <view class="reward-type-group">
            <view class="reward-type-item"  @click="orderData.rewardType = 1">
              <view class="cart-checkbox" :class="{'active': orderData.rewardType === 1}">
                <text class="iconfont icon-selected"></text>
              </view>
              <text>积分活动</text>  
            </view>
            <view class="reward-type-item" @click="orderData.rewardType = 2">
              <view class="cart-checkbox" :class="{'active': orderData.rewardType === 2 }">
                <text class="iconfont icon-selected"></text>
              </view>
              <text>返现活动</text>  
            </view>
          </view>
        </view>
        <view class="activity-count">
          可获得
          <text class="count-num">{{ rewardValue}}</text>
          <text v-if="orderData.rewardType === 2">元返现</text>
          <text v-if="orderData.rewardType === 1">个积分</text>
        </view>
      </template>
      <template v-if="type === 2">
         <view class="activity-item">
          <view class="item-label">我的积分</view>
          <view class="point-count"><text class="count-num">{{userPointCount}}个</text></view>
         </view>
         <view class="activity-item" v-if="userPointCount < totalPrice">
          <view class="point-hint">积分余额不足，不能下单哦</view>
         </view>
      </template>
      
    </view>
    <view class="footer">
      <view class="footer-content">
      <view class="footer-left">
        <view class="">共计{{totalNum}}件</view>
      </view>
      <view class="footer-right">
        <view class="footer-total">
          <text>合计：</text>
          <view class="price">
            <text v-if="type === 1" >￥</text>
            <text class="integer-price">{{priceData.integerPrice}}</text>
            <text class="decimal-price" v-if="priceData.decimalPrice !== 0">{{priceData.decimalPrice}}</text>
            <text v-if="type === 2" > 积分</text>
          </view>
        </view>
        <view class="footer-btn" :class="{'disabled': isBtnDisable}" @click="handleSubmit">提交订单</view>
      </view>
      </view>

    </view>
    <!-- <TabBar></TabBar> -->
    <Login />
    <HintDialog type="rewardTypeRule" :show="hintDialogShow" @cancel="()=> {hintDialogShow = false}" />
  </view>
</template>

<script setup>
import { reactive, ref, computed } from 'vue'
import { useStore } from 'vuex'
import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { getCartListApi, createOrderByCart, createOrderByProduct } from '@/api/user'
import { getProductDetailApi } from '@/api/product'
import ProductOrder from "../../components/product/ProductOrder.vue";

const store = useStore();
const sysConfig = computed(()=> {
  return store.state.app.config
})
const userPointCount = computed(()=> {
  return store.state.user.userPointCount
})
const isBtnDisable = computed(()=> {
  return type.value === 2 && userPointCount.value < totalPrice.value
})
const cartIds = ref([])
const pid = ref(null)
const hintDialogShow = ref(false)
const type = ref(1)
const cartProductList = ref([])

const selectedAddress = ref({})
const orderData = ref({
    "expressAddress": "",
    "expressReceiverName": "",
    "expressReceiverPhone": "",
    "orderType": 1,
    "rewardType": '',
    // "shoppingCartIds": cartIds.value
  })
const totalPrice = computed(()=> {
  let price = 0
  cartProductList.value.forEach(item=> {
    price += item.productAmount * item.price
  })
  return Number(price.toFixed(2))
})

const totalPriceAct = computed(()=> {
  let price = 0
  cartProductList.value.forEach(item=> {
    if(item.joinAct === 1) {
      price += item.productAmount * item.price
    }
    
  })
  return Number(price.toFixed(2))
})

const totalNum = computed(()=> {
  return cartProductList.value.reduce((sum, item) => sum + item.productAmount, 0)
})
const rewardValue = computed(()=> {
  let price = 0
  if(orderData.value.rewardType === 1) {
    price = sysConfig.value.order_credit_exchange_rate.value * totalPriceAct.value
  } else if(orderData.value.rewardType === 2){
    price = sysConfig.value.order_bonus_exchange_rate.value * totalPriceAct.value
  }
  return Number(price.toFixed(2))
})
const canGetPoint = computed(()=> {
  return cartProductList.value.every((item)=> item.joinAct === 1)
})
const priceData = computed(()=> {
  if(totalPrice.value) {
    const price = totalPrice.value.toFixed(2)
    const [ integerPrice, decimalPrice] = price.split('.')
    // return price.split('.')[0]
    return {
      integerPrice,
      decimalPrice: '.' + decimalPrice
    }
  }
  return  {
    integerPrice: 0,
    decimalPrice: 0,
  }
})
onLoad((options)=> {
  if(options.type){
    type.value = Number(options.type)
    orderData.value.orderType = type.value
  }
  if(options.cartIds){
    const ids = decodeURIComponent(options.cartIds)
    cartIds.value = ids.split(',').map((item)=> Number(item))
    // console.log('cartIds', cartIds.value)
    orderData.value.shoppingCartIds = cartIds.value
  } else if(options.pid) {
    pid.value = options.pid
    orderData.value.productBasicId = options.pid
    orderData.value.productAmount = 1
  } else {
    uni.$u.toast('访问错误！')
    setTimeout(()=> {
      uni.switchTab({
        url: '/pages/index/index',
      })
    }, 2000)
  }
  getAddressList()
  uni.$on('selectedAddress', (data)=> {
    //     "expressAddress": "",
    // "expressReceiverName": "",
    // "expressReceiverPhone": "",
    console.log(data)

    setAddressData(data)
  })
  init()
})

onPullDownRefresh( async ()=> {
  await init().finally(() => {
    uni.stopPullDownRefresh();
  });
})
async function init() {
  store.dispatch('user/getUserPointCount')
  if(cartIds.value.length){
    await getListData()
  }
  if(pid.value){
    await getProductData()
  }
}
async function getListData(){
  const res = await getCartListApi({
    page: 1,
    size: 1000,
    type: type.value
  })
  const list = res.items.filter((item)=> cartIds.value.includes(item.id))
  cartProductList.value = list
}
async function getAddressList(){
  const res = await store.dispatch('user/getAddressList')
  const defaultData = res.find((item) => item.isDefault === 1)
  if(defaultData) {
    setAddressData(defaultData)
  }
}
function setAddressData(data) {
  orderData.value.expressAddress = data.addressDetail
  orderData.value.expressReceiverName = data.receiverName
  orderData.value.expressReceiverPhone = data.receiverPhone
}
async function getProductData(){
  const res = await getProductDetailApi({'pid': pid.value})
  const productImageUrl = res.images.find(item=> item.type === 1)?.url || ''
  cartProductList.value = [ {
      // "id": 0,
      ...res,
      orderType: res.productType,
      productBasicId: res.id,
      productAmount: 1,
      productImageUrl
  }]
}


async function handleSubmit() {
  if(type.value === 2 && userPointCount.value < totalPrice.value) {
     uni.$u.toast('积分余额不足，不能下单哦')
    return false
  }
  if(!orderData.value.expressAddress) {
    uni.$u.toast('请选择地址！')
    return false
  }
  if(orderData.value.orderType === 1 && !orderData.value.rewardType) {
    uni.$u.toast('请选择奖励类型！')
    return false
  }
  if(!orderData.value.shoppingCartIds?.length && !orderData.value.productBasicId) {
    uni.$u.toast('下单错误，请返回首页重新下单！')
    return false
  }
  try {
    uni.showLoading()
    if(orderData.value.shoppingCartIds?.length) {
      await createOrderByCart({...orderData.value})
    } else if(orderData.value.productBasicId) {
      await createOrderByProduct({...orderData.value})
    } 
    uni.$u.toast('下单成功！')
  } finally{
      uni.hideLoading()
  }
  if(type.value === 1) {
    uni.switchTab({
      url: '/pages/order/index'
    });
  } else{
    uni.redirectTo({
      url: '/pages/point/order',
    })
  }


}
function handleToAddress(){
  uni.navigateTo({
    url: '/subpkgs/mine/address/list?selected=1',
  })
}
</script>

<style lang='scss' scoped>
.main{
  min-height: 100vh;
  background: #F4F6F8;
  padding-bottom: calc(140rpx + var(--safe-area-inset-bottom));
  .address{
    padding: 32rpx;
    background: #fff;
    margin-bottom: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .address-content{
      display: flex;
      .iconfont{
        color: #F27326;
        font-size: 28rpx;
      }
      .address-info{
        padding: 0 21rpx;
        .address-text{
          font-weight: 500;
          font-size: 28rpx;
          color: #333333;
          line-height: 36rpx;
          margin-bottom: 8rpx;
        }
        .address-user{
          font-weight: 400;
          font-size: 24rpx;
          color: #999999;
          line-height: 36rpx;
        }
      }
    }
    .address-null{
      font-weight: 500;
      font-size: 28rpx;
      color: #333333;
      line-height: 36rpx;
    }
    .null-hint{
      font-weight: 500;
      font-size: 28rpx;
      color: #333333;
    }
  }

  .products{
    padding: 32rpx;
    margin-bottom: 20rpx;
    background: #fff;
  }
  .cart-item {
    height: 140rpx;
    display: flex;
    margin-bottom: 24rpx;
    &:last-child{
      margin-bottom: 0;
    }
    .left{
      display: flex;
      align-items: center;
      justify-content: center;
      width: 104rpx;
      .item-checkbox{

      }
    }
    .product-item{
      flex: 1;
    }
    .minus,.plus {
      width: 44rpx;
      height: 44rpx;
      border-radius: 4rpx 4rpx 4rpx 4rpx;
      border: 1rpx solid #EEEEEE;
      @include flex;
      justify-content: center;
      align-items: center;
      font-size: 32rpx;
    }

    .input {
      width: 60rpx;
      height: 44rpx;
      text-align: center;
      border-top: 1rpx solid #EEEEEE;
      border-bottom: 1rpx solid #EEEEEE;
      box-sizing: border-box;
    }
  }
  .activity{
    padding: 32rpx;
    background: #fff;
    .activity-item{
      display: flex;
      justify-content: space-between;
      margin-bottom: 24rpx;
      .point-hint{
        font-weight: 400;
        font-size: 24rpx;
        color: #FA5151;
        line-height: 36rpx;
        margin-top: -8rpx;
      }
      &:last-child{
        margin-bottom: 0;
      }
      .item-label{
        font-weight: 400;
        font-size: 26rpx;
        color: #333333;
        line-height: 36rpx;
        .label-required{
          color: #FA5151;
          font-size: 20rpx;
          line-height: 1;
        }
        .iconfont{
          margin-left: 8rpx;
        }
      }
      .reward-type-group{
        display: flex;
        gap: 46rpx;
        .reward-type-item{
          font-weight: 400;
          font-size: 26rpx;
          color: #333333;
          line-height: 36rpx;
          display: flex;
          gap: 16rpx;
          .cart-checkbox{
            display: flex;
            width: 32rpx;
            height: 32rpx;
            align-items: center;
            justify-content: center;
            background: #fff;
            border: 1rpx solid #DCDCDC;
            color: #fff;
            border-radius: 50%;
            .iconfont{
              display: none;
            }
            &.active{
              border: 1rpx solid #FF8F1F;
              background: #FF8F1F;
              .iconfont{
                display: inline;
              }
            }
          }
        }
      }
    }
    .activity-count{
      text-align: right;
      font-weight: 400;
      font-size: 22rpx;
      color: #666666;
      line-height: 36rpx;
      .count-num{
        color: #FF8F1F;
      }
    }
    .point-count{
      font-weight: 400;
      font-size: 26rpx;
      color: #FF8F1F;
    }
  }
  .footer{
    position: fixed;
    bottom: 0;
    left: 0;
    background: #FFFFFF;
    box-sizing: content-box;
    padding-bottom: var(--safe-area-inset-bottom);
    align-items: center;
    .footer-content{
      height: 120rpx;
      width: 100vw;
      display: flex;
      padding: 24rpx 0;
      justify-content: space-between;
    }
    .footer-left{
      padding: 0 32rpx;
      display: flex;
      font-weight: 400;
      font-size: 26rpx;
      color: #333333;
      line-height: 36rpx;
      align-items: center;
      gap: 12rpx;
      .checkbox{
        width: 40rpx;
        height: 40rpx;
        background: #EEEEEE;
        border: 2rpx solid #999999;
        margin-right: 12rpx;
      }
    }
    .footer-right{
      display: flex;
      padding-right: 32rpx;
      // flex: 1;
      .footer-total{
        display: flex;
        margin-right: 36rpx;
        align-items: center;
        font-weight: 400;
        font-size: 26rpx;
        color: #333333;
        .price{
          font-weight: 400;
          font-size: 24rpx;
          color: #FA5151;
          line-height: 36rpx;
          .integer-price{
            font-size: 48rpx
          }
          .decimal-price{
            font-size: 32rpx
          }
        }
      }
      .footer-btn{
        width: 180rpx;
        height: 72rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #EE0A24;
        border-radius: 55rpx;
        font-size: 26rpx;
        color: #FFFFFF;
        &.disabled{
          background: #DCDCDC;
        }
      }
    }
  }
}
</style>
